# -*- coding: utf-8 -*-

from django import template

register = template.Library()

class IfPermissionNode(template.Node):
    def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
        self.var1, self.var2 = var1, var2
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
        self.negate = negate

    def __repr__(self):
        return "<IfPermissionNode>"

    def render(self, context):
        user = self.var1.resolve(context, True)
        actions = self.var2.resolve(context, True)
        if isinstance(actions, str) or isinstance(actions, unicode):
            actions = actions.split()
        try:
            result = user.tem_permissao(actions)
        except:
            result = False
        if (self.negate and not result) or (not self.negate and result):
            return self.nodelist_true.render(context)
        return self.nodelist_false.render(context)


def do_ifpermission(parser, token, negate):
    bits = list(token.split_contents())
    if len(bits) != 3:
        raise template.TemplateSyntaxError, "%r takes two arguments" % bits[0]
    end_tag = 'end' + bits[0]
    nodelist_true = parser.parse(('else', end_tag))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    val1 = parser.compile_filter(bits[1])
    val2 = parser.compile_filter(bits[2])
    return IfPermissionNode(val1, val2, nodelist_true, nodelist_false, negate)


@register.tag(name='ifpermission')
def ifpermission(parser, token):
    return do_ifpermission(parser, token, False)

@register.tag(name='ifnotpermission')
def ifnotpermission(parser, token):
    return do_ifpermission(parser, token, True)


